/**
 * * 图片懒加载指令
 */
import {eventBus} from "@/utils"
import {debounce} from "@/utils"
import defaultImg from "@/assets/default.gif"
let imgs = [];

function handleScroll() {
    setImgs();
}

function setImgs() {
    for(let item of imgs) {
        // 处理每张图片
        item.dom.src = defaultImg;
        setImg(item)
    }
}

function setImg(img) {
    const rect = img.dom.getBoundingClientRect();
    
    const clientHeight = document.documentElement.clientHeight;
    const height = rect.height || 110;
    if(rect.top >= -height && rect.top <= clientHeight) {
        img.dom.src = img.src;
        imgs = imgs.filter((i) => i !== img);
    }
}


eventBus.$on("mainScroll", debounce(handleScroll, 60) );

export default {
    inserted(el, binding) {
        const imgObj = {
            dom: el,
            src: binding.value
        };
        imgs.push(imgObj);
        setImgs();
    },
    unbind(el) {
        imgs = imgs.filter((img) => img.dom !== el);
    }
}
